package cn.tannn.ops.quartz.job;

import cn.tannn.ops.backup.service.DbBackupService;
import cn.tannn.ops.quartz.annotation.Job;
import cn.tannn.ops.quartz.annotation.JobMeta;
import cn.tannn.ops.ssh.service.SshInfoService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

/**
 * 数据库备份任务
 * @author <a href="https://t.tannn.cn/">tan</a>
 * @version V1.0
 * @date 2024/8/27 上午9:36
 */
@Slf4j
@Component
@Job(cron = "0 5 0 * * ?", jobName = "DbBackupJob", isStartNow = false)
@JobMeta(name = "数据库数据备份", description = "数据库备份")
public class DbBackupJob extends QuartzJobBean {

    private final DbBackupService dbBackupService;
    private final SshInfoService sshInfoService;

    public DbBackupJob(DbBackupService dbBackupService
            , SshInfoService sshInfoService) {
        this.dbBackupService = dbBackupService;
        this.sshInfoService = sshInfoService;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.debug("Executing  DbBackupJob");
        dbBackupService.finds().forEach(dbBackup -> {
            try {
                if(dbBackup.getSshId() != null ){
                    sshInfoService.findOnly("id", dbBackup.getSshId()).ifPresent(ssh -> {
                        dbBackupService.backup(dbBackup,ssh);
                    });
                }
            }catch (Exception e){
              log.error("%s数据库备份失败",dbBackup.getName(),e);
            }
        });
    }
}
